Sh.User.Input = new Class({
	initialize : function (user) {
		this.engine = user.engine;
		this.user   = user;
		this.createTextarea();
		this.printText();
	},
	getElement : function () {
		if (!this.element) {
			this.element = this
				.engine
				.terminal
				.getUserInput();
		}
		return this.element;
	},
	printText : function (text, selection) {
		var selectionElem = this.getSelectionElement(text, selection);
		var greetElem     = this.user.greeting.getElement();
		var uinput = this.getElement()
				.empty()
				.append(greetElem)
				.append('&nbsp;');
		if (text) {
			uinput
				.append(
					this.prepareUserInput(
						text.substring(0, selection.start)
					)
				)
				.append(selectionElem)
				.append(
					this.prepareUserInput(
						text.substring(selection.end)
					)
				);
		} else {
			uinput
				.append(selectionElem)
				.append('&nbsp;')
		}

		return this;
	},
	prepareUserInput : function (text) {
		return text
			.safeHTML()
			.replaceAll('\n', '<br/>\n&gt; ')
			.replaceAll(' ', '&nbsp;');
	},
	getSelectionElement : function (text, selection) {
		if (!selection) {
			selection = {
				start : 0,
				end   : 0
			};
		}
		var selectionElem = $('<selection>').html(
			!$chk(text) ? '' : this.prepareUserInput(text
				.substring(selection.start, selection.end))
		);

		$clear(this.selectionTimer);
		this.selectionTimer = function () {
			selectionElem.toggleClass('hide')
		}.periodical(500);
		return selectionElem;
	},
	addValue : function (text, selection) {
		return this.setValue(
			this.getValue() + text, selection
		);
	},
	setValue : function (text, selection) {
		this.textarea.val(text);
		if (selection) {
			if (['number', 'string'].contains(typeof selection)) {
				if (selection.toLowerCase() == 'max') {
					selection = text.length;
					if (Browser.Engine.presto) { // fucking opera
						selection++;
					}
				} else {
					selection*= 1;
					selection = Math.max(text.length, selection);
				}
				selection = [selection, selection];
			} else if ($chk(selection.start)) {
				selection = [selection.start, selection.end];
			}
			this.textarea.each(function () {
				this.selectionStart = selection[0];
				this.selectionEnd   = selection[1];
			});

		}
		return this;
	},
	getValue : function () {
		return this.textarea.val();
	},
	clear : function () {
		return this.setValue('', 0);
	},
	createTextarea : function () {
		var $this = this;
		var changedInput = function (e) {
			$this.printText(this.value, {
				start : this.selectionStart,
				end   : this.selectionEnd
			});
		};

		this.textarea = $('<textarea>')
			.css({
				position : 'absolute',
				left     : -9999
			})
			.bind('input', changedInput)
			.bind('dragdrop', changedInput)
			.bind('keypress', changedInput)
			.bind('keydown', changedInput)
			.bind('keyup', changedInput)
			.appendTo($('office'));

		$(document).keydown(function () {
			this.textarea.focus();
		}.bind(this));

		return this;
	}

});
 
